package org.setamv.springcloud.controller;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.net.URI;

@RestController
@RequestMapping("/work")
public class WorkController {

    private static final Logger LOGGER = LoggerFactory.getLogger(WorkController.class);

    @Value("${spring.application.id}")
    private String applicationId;

    @Value("${service.delegate.url}")
    private String delegateUrl;

    @Autowired
    HttpClient httpClient;

    @Autowired
    OkHttpClient okHttpClient;

    @RequestMapping(value = "", method = RequestMethod.GET)
    public String work() throws Exception {
        return "Work at [" + applicationId + "].";
    }

    /**
     * 睡眠10秒后返回，用于测试延迟的熔断，例如hystrix
     */
    @RequestMapping(value = "/for/{milliseconds}", method = RequestMethod.GET)
    public String workForSeconds(@PathVariable int milliseconds) throws Exception {
        Thread.sleep(milliseconds);
        return "Work at [" + applicationId + "] for " + milliseconds + "(ms).";
    }

    /**
     * 测试直接通过HttpClient发送请求
     */
    @RequestMapping(value = "/httpclient", method = RequestMethod.GET)
    public String workByHttpClient() throws Exception {
        String url = delegateUrl + "/work";
        HttpGet httpGet = new HttpGet(url);
        HttpResponse response = httpClient.execute(httpGet);
        return EntityUtils.toString(response.getEntity());
    }

    /**
     * 测试直接通过OKHttpClient发送请求
     */
    @RequestMapping(value = "/okhttpclient", method = RequestMethod.GET)
    public String workByOkHttpClient() throws Exception {
        String url = delegateUrl + "/work";
        Request request = new Request.Builder()
                .url(url)
                .build();
        Response response = okHttpClient.newCall(request).execute();
        return response.body().string(); // 返回的是string 类型，json的mapper可以直接处理
    }

}
